<template>
	<view class="body">
		<view class="container">
			<view class="type">
				<view :class="['type-item',type=== 0 ? 'type-select' :'']" @click="toggleActive(0)">寻物</view>
				<view :class="['type-item',type=== 1 ? 'type-select' :'']" @click="toggleActive(1)">寻主</view>
			</view>
			<view class="classify">
				<text class="label">物品类别：</text>
				<!-- 多列选择器 -->
				<picker class="picker" @columnchange="bindPickercolumnChange" @change="bindPickerChange"
					@:value="arryindex" :range="array" mode="multiSelector">
					<view class="picker-item">
						<view class="select" v-if="select">
							{{array[0][arryindex[0]]}} / {{array[1][arryindex[1]]}}
							<!-- <uni-icons class="trash-icon" type="trash" size="22" @click.stop="closeselect"></uni-icons> -->
							<image src="../../static/pic/trash-icon.png" mode="" class="trash-icon"
								@click.stop="closeselect"></image>
						</view>
						<!-- 没选择时的默认样式 -->
						<view class="empty" v-else>
							<text>请选择</text>
							<uni-icons type="down" size="22"></uni-icons>
						</view>
					</view>
				</picker>
			</view>
			<view class="input-list">
				<view class="input-item">
					<input @input="getName" :value="name" type="text" placeholder="请输入物品名称" />
					<view class="error-tips" v-if="name_check">请输入少于20字的物品名称</view>
				</view>

				<view class="input-item">
					<input @input="getDate" :value="date" type="text" placeholder="请输入丢失/拾取地时间" />
					<view class="error-tips" v-if="date_check">请输入少于20字的时间点</view>
				</view>
				<view class="input-item">
					<input @input="getRegion" :value="region" type="text" placeholder="请输入丢失/拾取地点" />
					<view class="error-tips" v-if="region_check">请输入少于20字的地点</view>
				</view>
				<view class="input-item">
					<input @input="getPhone" :value="phone" type="text" placeholder="联系方式,微信/QQ/手机号" />
					<view class="error-tips" v-if="phone_check">请输入少于30字的联系方式</view>
				</view>

			</view>
			<view class="desc">
				<textarea @input="getDesc" :value="desc" placeholder="请输入物品描述" id="" cols="25" rows="10"></textarea>
				<!-- trim() 去除空白字符串-->
				<image v-if="desc.length > 0" class="close-icon" src="../../static/pic/close2.png" mode=""
					@click="cleandesc"></image>
			</view>
			<view class="upload">
				<view class="upload-top">
					<text>最多选择6张图片</text>
					<text>{{imglist.length}}/6</text>
				</view>
				<view class="upload-list">
					<view class="img-list" v-for="(item,i) in imglist" :key="i">
						<image class="common" :src="item" mode=""></image>
						<image class="detele" src="../../static/pic/close.png" mode="" @click="deletImg(i)"></image>
					</view>
					<image class="default" src="../../static/pic/upload.png" mode="" @click="uploadImg"
						v-if="imglist.length<6"></image>
				</view>
			</view>
		</view>
		<view class="bottom">
			<button class="push-btn" size="mini" @click="toPublish">{{ID?"修改" : "发布"}}</button>
			<button size="mini" v-if="ID" class="cancel" @click="cancellation">取消修改</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		onLoad,
		onShow,
		onUnload
	} from '@dcloudio/uni-app';
	import {
		http
	} from '../../API/request.js'
	// 数据
	const name = ref('')
	const date = ref('')
	const region = ref('')
	const phone = ref('')
	const desc = ref('')
	const imglist = ref([])
	const select = ref(false)
	const type = ref(0)
	const classify1 = ref('')
	const classify2 = ref('')
	const name_check = ref(false)
	const date_check = ref(false)
	const region_check = ref(false)
	const phone_check = ref(false)
	const updataid = ref('')
	const currentTime = new Date();
	const timestamp = currentTime.getTime()
	const openid = uni.getStorageSync('openid')
	const login = ref(false)
	const ID = ref('')
	// const formattedDate = currentTime.toLocaleDateString('zh-CN', {
	// 	year: 'numeric',
	// 	month: '2-digit',
	// 	day: '2-digit'
	// })
	const array = ref([
		['证件', '生活用品', '数码产品', '美妆护肤品', '衣服物品', '饰品', '文娱', '其他'],
		['身份证', '校园卡', '学生证', '水卡', '公交卡', '银行卡', '其他']
	])
	const array2 = ref([
		['身份证', '校园卡', '学生证', '水卡', '公交卡', '银行卡', '其他'],
		['水杯', '雨伞', '小风扇', '钥匙', '其他'],
		['手机', '相机', 'u盘', '充电宝', '平板电脑', '鼠标', '充电线', '耳机', '手写笔', '支架', '音箱', 'MP3', '其他'],
		['口红', '粉底', '眉笔', '腮红', '眼影', '防嗮', '喷雾', '香水', '其他'],
		['男装', '女装', '男鞋', '女鞋', '包包', '其他'],
		['手表', '项链', '收链', '戒指', '耳饰', '眼镜', '帽子', '发饰', '其他'],
		['教材', '笔记', '文具', '球拍/球', '护具', '跳绳', '自行车', '其他'],
		['药品', '零食', '周边', '其他']
	])
	const arryindex = ref([0, 0])
	// 事件
	const cancellation = () => {
		uni.removeStorageSync('updataid')
		name.value = '';
		date.value = '';
		region.value = '';
		phone.value = '';
		desc.value = '';
		imglist.value = [];
		ID.value = '',
			select.value = false,
			type.value = 0
	}
	const getName = (e) => {
		// trim() 去除空白字符串
		name.value = e.detail.value.trim()
		name_check.value = false
	}
	const getDate = (e) => {
		date.value = e.detail.value.trim()
		date_check.value = false
	}
	const getRegion = (e) => {
		region.value = e.detail.value.trim()
		region_check.value = false
	}
	const getPhone = (e) => {
		phone.value = e.detail.value.trim()
	}
	const getDesc = (e) => {
		desc.value = e.detail.value.trim()
		phone_check.value = false
	}
	const cleandesc = () => {
		desc.value = ''
	}
	const closeselect = () => {
		select.value = false
		arryindex.value = [0, 0]
	}

	const bindPickerChange = () => {
		select.value = true
	}
	const bindPickercolumnChange = (e) => {
		const {
			column,
			value
		} = e.detail
		// 左侧的column为0，右侧为1
		if (column === 0) {
			// 当colum为零的时候，就是滑动左侧的时候，根据左侧的value将array2中的对应那一项赋值到array.value[1]中
			array.value[1] = array2.value[value]
		}
		// 将更改array.value[1]后的数组赋值给原数组
		array.value = array.value
		// column对应0和1，也就是对应arryindex数组的两个数据，当滑动左右两侧时，column会变化，然后再根据value对数组进行赋值更新
		arryindex.value[column] = value
	}
	const deletImg = (i) => {
		imglist.value.splice(i, 1)
	}
	// 发布数据，将数据发到后端
	const toPublish = () => {
		if (!login.value) {
			uni.showToast({
				title: '请先登陆',
				icon: 'none'
			})
			return
		} else {
			if (!name.value) {
				name_check.value = true
			}
			if (!date.value) {
				date_check.value = true
			}
			if (!region.value) {
				region_check.value = true
			}
			if (!phone.value) {
				phone_check.value = true
			}
			if (!name.value || !select.value || !date.value || !region.value || !phone.value) {
				uni.showToast({
					title: '未填写必填项',
					icon: 'none'
				})
				return
			}
			if (ID.value) {
				http.post('/updateLose', {
					type: Number(type.value),
					classify1: array.value[0][arryindex.value[0]],
					classify2: array.value[1][arryindex.value[1]],
					name: name.value,
					date: date.value,
					region: region.value,
					phone: phone.value,
					desc: desc.value,
					imgList: imglist.value,
					time: timestamp,
					openid: openid,
					id: ID.value
				}).then((res) => {
					const {
						data
					} = res;
					if (data === "success") {
						uni.switchTab({
							url: '/pages/home/home',
							success: () => {
								uni.showToast({
									icon: 'none',
									title: '修改成功'
								});
								// 清空输入字段
								name.value = '';
								date.value = '';
								region.value = '';
								phone.value = '';
								desc.value = '';
								imglist.value = [];
								ID.value = ''
								// 重置其他状态变量
								name_check.value = false;
								date_check.value = false;
								region_check.value = false;
								phone_check.value = false;
								select.value = false;
								arryindex.value = [0, 0];
								uni.removeStorageSync('updataid')
							}
						});
					} else {
						uni.showToast({
							icon: 'none',
							title: '修改失败'
						});
					}
				}).catch((error) => {
					// 处理请求错误
					console.error('发布失败:', error);
					uni.showToast({
						icon: 'none',
						title: '网络错误或服务器无响应'
					});
				});
			} else {
				http.post('/publish', {
					type: Number(type.value),
					classify1: array.value[0][arryindex.value[0]],
					classify2: array.value[1][arryindex.value[1]],
					name: name.value,
					date: date.value,
					region: region.value,
					phone: phone.value,
					desc: desc.value,
					imgList: imglist.value,
					time: timestamp,
					openid: openid
				}).then((res) => {
					const {
						data
					} = res;
					if (data === "success") {
						uni.switchTab({
							url: '/pages/home/home',
							success: () => {
								uni.showToast({
									icon: 'none',
									title: '发布成功'
								});
								// 清空输入字段
								name.value = '';
								date.value = '';
								region.value = '';
								phone.value = '';
								desc.value = '';
								imglist.value = [];
								// 重置其他状态变量
								name_check.value = false;
								date_check.value = false;
								region_check.value = false;
								phone_check.value = false;
								select.value = false;
								arryindex.value = [0, 0];
							}
						});
					} else {
						uni.showToast({
							icon: 'none',
							title: '发布失败'
						});
					}
				}).catch((error) => {
					// 处理请求错误
					console.error('发布失败:', error);
					uni.showToast({
						icon: 'none',
						title: '网络错误或服务器无响应'
					});
				});
			}
		}
	}

	const uploadImg = () => {
		if (!login.value) {
			uni.showToast({
				title: '请先登陆',
				icon: 'none'
			})
			return
		} else {
			uni.chooseMedia({
				count: 6 - imglist.value.length,
				mediaType: ['image'],
				sourceType: ['album', 'camera'],
				success(res) {
					const {
						tempFiles
					} = res
					tempFiles.forEach((item, index) => {
						// 上传图片到服务器
						uni.uploadFile({
							url: 'http://localhost:80/uploadImg',
							filePath: item.tempFilePath,
							name: 'file',
							success: (res) => {
								const {
									data
								} = res
								let {
									path
								} = JSON.parse(res.data)[0]
								let _path =
									`http://localhost:80/${path.replace(/\\/g, '/')}`
								imglist = imglist.value.push(_path)
							}
						});
					})

				}
			})
		}

	}
	const toggleActive = (index) => {
		if (index === 0) {
			type.value = 0
		} else if (index === 1) {
			type.value = 1
		}
	}

	onLoad((options) => {
		updataid.value = uni.getStorageSync('updataid')
		login.value = !!uni.getStorageSync('login')
		const userdata = uni.getStorageSync('userinfo')
		if (userdata && userdata.inputValue) {
			phone.value = userdata.inputValue
		}
		const id = uni.getStorageSync('updataid')
		ID.value = id
		if (id) {
			http.post('/getDetail', {
				_id: id
			}).then((res) => {
				const {
					data
				} = res
				select.value = true
				type.value = data.type
				classify1.value = data.classify1
				classify2.value = data.classify2
				const index1 = array.value[0].findIndex(item => item === classify1.value)
				const index2 = array2.value[index1].findIndex(item => item === classify2.value)
				arryindex.value = [index1, index2]
				array.value = [
					array.value[0],
					array2.value[index1]
				]
				name.value = data.name
				date.value = data.date
				region.value = data.region
				phone.value = data.phone
				desc.value = data.desc
				imglist.value = data.imgList
			})
		}
		// 设置 scrollTop 为 0 来滚动到顶部
		uni.pageScrollTo({
			scrollTop: 0, // 设置滚动到顶部
			duration: 300 // 动画时长，单位毫秒
		})
	})
	onShow(() => {
		login.value = !!uni.getStorageSync('login')
		const id = uni.getStorageSync('updataid')
		if (id) {
			ID.value = id
		}
		if (id) {
			http.post('/getDetail', {
				_id: id
			}).then((res) => {
				const {
					data
				} = res
				select.value = true
				type.value = data.type
				classify1.value = data.classify1
				classify2.value = data.classify2
				const index1 = array.value[0].findIndex(item => item === classify1.value)
				const index2 = array2.value[index1].findIndex(item => item === classify2.value)
				arryindex.value = [index1, index2]
				array.value = [
					array.value[0],
					array2.value[index1]
				]
				name.value = data.name
				date.value = data.date
				region.value = data.region
				phone.value = data.phone
				desc.value = data.desc
				imglist.value = data.imgList
			})
		}
	})
	onUnload(() => {
		uni.removeStorageSync('updataid')
	})
</script>

<style lang="less">
	.body {
		width: 100vw;
		min-height: 100vh;
		background-color: #fff;

		.bottom {
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 30rpx 20rpx;
			width: 100%;
			box-sizing: border-box;
			border-bottom: 5rpx solid #f3f3f3;
			font-size: 50rpx;


			.push-btn {
				margin: 0 !important;
				background-color: skyblue;
				color: #fff;
				border-radius: 40rpx;
				width: 300rpx;
			}

			.cancel {
				position: fixed;
				bottom: 40px;
				right: 20px;
			}
		}

		.container {
			padding: 30rpx 35rpx 50rpx 35rpx;

			.type {
				display: flex;

				.type-item {
					background-color: #eee;
					padding: 10rpx 70rpx;
					border: 1px solid #aaa;
					margin-right: 30rpx;
					border-radius: 10rpx;
				}

				.type-select {
					background-color: skyblue;
					color: #fff;
				}
			}

			.classify {
				margin-top: 50rpx;
				display: flex;
				width: 100%;
				align-items: center;

				.label {
					margin-right: 20rpx;
					white-space: nowrap;
				}

				.picker {
					width: 100%;

					.empty,
					.select {
						display: flex;
						border: 2px solid #aaa;
						width: 100%;
						padding: 10rpx 20rpx;
						box-sizing: border-box;
						border-radius: 15rpx;
						justify-content: space-between;
						align-items: center;

						.trash-icon {
							z-index: 19;
							width: 50rpx;
							height: 50rpx;
						}

					}
				}
			}

			.input-list {
				padding: 20rpx 15rpx;
				padding-top: 20rpx;
				border-bottom: 2px solid #f3f3f3;

				.input-item {
					margin-bottom: 20rpx;

					.error-tips {
						color: #f00;
						font-size: 26rpx;
					}
				}
			}

			.desc {
				padding: 20rpx 15rpx;
				border-bottom: 2px solid #f3f3f3;
				position: relative;

				.close-icon {
					width: 40rpx;
					height: 40rpx;
					position: absolute;
					top: 30rpx;
					right: 0;
				}
			}

			.upload {
				padding-top: 20rpx;

				.upload-top {
					display: flex;
					justify-content: space-between;
				}

				.upload-list {
					display: flex;
					flex-wrap: wrap;
					margin-top: 20rpx;

					.img-list {
						width: 33%;
						height: 200rpx;
						position: relative;

						.common {
							width: 100%;
							height: 100%;
						}

						.detele {
							width: 40rpx;
							height: 40rpx;
							position: absolute;
							top: 0;
							right: 0;
							z-index: 10;
						}
					}

					.default {
						width: 33%;
						height: 200rpx;
					}
				}
			}
		}
	}
</style>